/*
 *  Copyright (C) 2010 Zubanov Dmitry
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
/**
 *
 * @author Zubanov Dmitry aka javadimon, zubanov@gmail.com
 * Omsk, Russia, created 29.05.2010
 * (C) Copyright by Zubanov Dmitry
 */
package org.jssdb.core.handler;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.jssdb.core.DBProperties;
import org.jssdb.core.FileStorage;
import org.jssdb.core.utils.FileInfo;

/**
 *
 * @author Zubanov Dmitry aka javadimon, zubanov@gmail.com
 * Omsk, Russia,
 * created 08.05.2010
 */
public class FileStorageHandler implements FileStorage {

    private static FileStorageHandler self = null;
    private static final Logger logger = Logger.getLogger(FileStorageHandler.class.getName());
    private Map<File, Long> mBoost = new HashMap<File, Long>();
    private int autoStart = 0, autoIncrement = 0, autoOffset = 1;

    private FileStorageHandler() {
        //
    }

    public static FileStorageHandler getDefault() {
        if (self == null) {
            self = new FileStorageHandler();
        }

        return self;
    }

    public void setIdOffset(int autoStart, int autoIncrement, int autoOffset) {
        this.autoStart = autoStart;
        this.autoIncrement = autoIncrement;
        this.autoOffset = autoOffset;
    }

    /**
     * 
     * @param obj
     * @return
     */
    public FileInfo getSaveFileInfo(File f) {
        long number = 0;

        // get max file number
        if (mBoost.get(f) == null) {
            number = getMax(f);
        } else {
            number = mBoost.get(f) + 1;
        }

        long newId = 0;
        if (number < autoStart) {
            newId = autoStart;

        } else if (number == autoStart) {
            newId = autoStart + autoIncrement + autoOffset;

        } else if (number > autoStart) {
            if ((number % autoOffset) == 0) {
                newId = (number - (number % autoOffset)) + autoIncrement;
            } else {
                newId = (number - (number % autoOffset)) + autoIncrement + autoOffset;
            }
        }

        mBoost.put(f, newId);

        return new FileInfo(f + File.separator + newId, newId);
    }

    public long getMax(File f) {
        File files[] = f.listFiles();
        long number = 0;

        if (files.length > 0) {
            for (File file : files) {
                long i = Long.valueOf(file.getName());
                if (i > number) {
                    number = i;
                }
            }
        }

        number = number + 1;

        return number;
    }

    public String getLoadFile(long id, Class cls) {
        String fileName = null;
        if (cls == null) {
            return fileName;
        }

        File f = new File(DBProperties.getInstance().getPathToDB() + cls.getName() + File.separator + id);
        if (!f.isFile()) {
            return null;
        }

        try {
            fileName = f.getCanonicalPath();
        } catch (Exception e) {
            logger.log(Level.SEVERE, cls.getName(), e);
        }

        return fileName;
    }

    public boolean deleteFile(long id, String className) {
        if (className == null) {
            return false;
        }

        File f = new File(DBProperties.getInstance().getPathToDB() + className + File.separator + id);
        if (!f.isFile()) {
            return false;
        }

        return f.delete();
    }

    public boolean deleteFile(long id, Class cls) {
        if (cls == null) {
            return false;
        }
        return deleteFile(id, cls.getName());
    }

    public long getMinId(String className) {
        if (className == null) {
            return -1;
        }

        File f = new File(DBProperties.getInstance().getPathToDB() + className);

        if (!f.isDirectory()) {
            return -1;
        }

        // get max file number
        long number = 0;
        File files[] = f.listFiles();

        if (files.length > 0) {
            ArrayList<Long> a = new ArrayList<Long>();
            for (File file : files) {
                a.add(Long.parseLong(file.getName()));
            }
            number = Collections.min(a);
        }

        return number;
    }

    public long getMinId(Class cls) {
        if (cls == null) {
            return -1;
        }

        return getMinId(cls.getName());
    }

    public long getMaxId(String className) {
        if (className == null) {
            return -1;
        }

        File f = new File(DBProperties.getInstance().getPathToDB() + className);

        if (!f.isDirectory()) {
            return -1;
        }

        // get max file number
        long number = 0;
        File files[] = f.listFiles();

        if (files.length > 0) {
            ArrayList<Long> a = new ArrayList<Long>();
            for (File file : files) {
                a.add(Long.parseLong(file.getName()));
            }
            number = Collections.max(a);
        }

        return number;
    }

    public long getMaxId(Class cls) {
        if (cls == null) {
            return -1;
        }

        return getMaxId(cls.getName());
    }

    public ArrayList<File> getFileList(long idFrom, long idTo, String className) {
        if (className == null) {
            return null;
        }

        File f = new File(DBProperties.getInstance().getPathToDB() + className);
        if (!f.isDirectory()) {
            return null;
        }
        File files[] = f.listFiles();
        if (files.length == 0) {
            return null;
        }

        ArrayList<File> fileList = new ArrayList();
        fileList.addAll(Arrays.asList(files));
        Collections.sort(fileList, new Comparator() {

            public int compare(Object o1, Object o2) {
                int val = 0;
                File f1 = (File)o1;
                File f2 = (File)o2;
                long l1 = Long.parseLong(f1.getName());
                long l2 = Long.parseLong(f2.getName());
                if(l1 > l2){
                    val = 1;
                } else {
                    val = -1;
                }
                return val;
            }
        });

        ArrayList<File> fileListOut = new ArrayList();
        for(File fCheck : fileList){
            long val = Long.parseLong(fCheck.getName());
            if(val >= idFrom && val <= idTo){
                fileListOut.add(fCheck);
            }
        }

        return fileListOut;
    }

    public ArrayList<File> getAllFilesList(String className) {
        if (className == null) {
            return null;
        }

        File f = new File(DBProperties.getInstance().getPathToDB() + className);
        if (!f.isDirectory()) {
            return null;
        }
        File files[] = f.listFiles();
        if (files.length == 0) {
            return null;
        }

        ArrayList<File> fileList = new ArrayList();
        fileList.addAll(Arrays.asList(files));
        Collections.sort(fileList, new Comparator() {

            public int compare(Object o1, Object o2) {
                int val = 0;
                File f1 = (File)o1;
                File f2 = (File)o2;
                long l1 = Long.parseLong(f1.getName());
                long l2 = Long.parseLong(f2.getName());
                if(l1 > l2){
                    val = 1;
                } else {
                    val = -1;
                }
                return val;
            }
        });

        return fileList;
    }

    public ArrayList<File> getFileList(long idFrom, long idTo, Class cls) {
        if (cls == null) {
            return null;
        }

        return getFileList(idFrom, idTo, cls.getName());
    }
}
